import request from '@/utils/request.js'
import upload from '@/utils/upload.js'
import platform from '@/utils/platform.js'

// 选择并上传图片
export function chooseAndUploadImage(options = {}) {
  return upload.chooseAndUploadImage({
    count: options.count || 9,
    ...options
  })
}

// 上传图片（使用若依的通用上传接口）
export function uploadImage(filePath, formData = {}) {
  return upload.uploadFile(filePath, {
    formData: {
      type: 'image',
      ...formData
    }
  })
}

// 上传视频
export function uploadVideo(filePath, formData = {}) {
  return upload.uploadFile(filePath, {
    formData: {
      type: 'video',
      ...formData
    }
  })
}

// 上传文件
export function uploadFile(filePath, formData = {}) {
  return upload.uploadFile(filePath, {
    formData: {
      type: 'file',
      ...formData
    }
  })
}

// 上传用户头像
export function uploadAvatar(filePath) {
  return upload.uploadFile(filePath, {
    formData: {
      type: 'avatar'
    }
  })
}

// 上传圈子头像
export function uploadTopicAvatar(filePath, topicId) {
  return upload.uploadFile(filePath, {
    formData: {
      type: 'topic_avatar',
      topicId: topicId
    }
  })
}

// 上传圈子封面
export function uploadTopicCover(filePath, topicId) {
  return upload.uploadFile(filePath, {
    formData: {
      type: 'topic_cover',
      topicId: topicId
    }
  })
}

// 选择图片（不上传）
export function chooseImage(options = {}) {
  return upload.chooseImage(options)
}

// 压缩图片
export function compressImage(filePath, quality = 0.8) {
  return upload.compressImage(filePath, quality)
}

// 获取图片信息
export function getImageInfo(src) {
  return upload.getImageInfo(src)
}

// 批量上传图片
export function uploadImages(tempFilePaths, options = {}) {
  return upload.uploadImages(tempFilePaths, options)
}

// 平台特定的文件选择
export function chooseFile(options = {}) {
  return new Promise((resolve, reject) => {
    const currentPlatform = platform.getPlatform()
    
    // #ifdef MP-WEIXIN
    // 微信小程序选择文件
    uni.chooseMessageFile({
      count: options.count || 10,
      type: options.type || 'all',
      success: resolve,
      fail: reject
    })
    // #endif
    
    // #ifdef H5
    // H5环境选择文件
    const input = document.createElement('input')
    input.type = 'file'
    input.multiple = (options.count || 1) > 1
    
    if (options.accept) {
      input.accept = options.accept
    }
    
    input.onchange = (e) => {
      const files = Array.from(e.target.files)
      const tempFiles = files.map(file => ({
        path: URL.createObjectURL(file),
        name: file.name,
        size: file.size,
        type: file.type,
        file: file
      }))
      
      resolve({
        tempFilePaths: tempFiles.map(f => f.path),
        tempFiles: tempFiles
      })
    }
    
    input.click()
    // #endif
    
    // #ifdef APP-PLUS
    // APP环境选择文件
    plus.gallery.pick((path) => {
      resolve({
        tempFilePaths: [path],
        tempFiles: [{
          path: path,
          name: path.split('/').pop(),
          size: 0
        }]
      })
    }, reject, {
      filter: options.type || 'image'
    })
    // #endif
  })
}

// 预览图片
export function previewImage(urls, current = 0) {
  return new Promise((resolve, reject) => {
    uni.previewImage({
      urls: Array.isArray(urls) ? urls : [urls],
      current: typeof current === 'number' ? urls[current] : current,
      success: resolve,
      fail: reject
    })
  })
}

// 保存图片到相册
export function saveImageToPhotosAlbum(filePath) {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    // 微信小程序需要先授权
    uni.authorize({
      scope: 'scope.writePhotosAlbum',
      success: () => {
        uni.saveImageToPhotosAlbum({
          filePath: filePath,
          success: resolve,
          fail: reject
        })
      },
      fail: () => {
        uni.showModal({
          title: '提示',
          content: '需要您授权保存相册',
          showCancel: false,
          success: () => {
            uni.openSetting({
              success: (settingdata) => {
                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                  uni.saveImageToPhotosAlbum({
                    filePath: filePath,
                    success: resolve,
                    fail: reject
                  })
                } else {
                  reject(new Error('用户拒绝授权'))
                }
              }
            })
          }
        })
      }
    })
    // #endif
    
    // #ifdef H5
    // H5环境下载图片
    const link = document.createElement('a')
    link.href = filePath
    link.download = `image_${Date.now()}.jpg`
    link.click()
    resolve()
    // #endif
    
    // #ifdef APP-PLUS
    // APP环境保存到相册
    uni.saveImageToPhotosAlbum({
      filePath: filePath,
      success: resolve,
      fail: reject
    })
    // #endif
  })
}

export default {
  chooseAndUploadImage,
  uploadImage,
  uploadVideo,
  uploadFile,
  uploadAvatar,
  uploadTopicAvatar,
  uploadTopicCover,
  chooseImage,
  compressImage,
  getImageInfo,
  uploadImages,
  chooseFile,
  previewImage,
  saveImageToPhotosAlbum
}